package com.example.mqttdemo.controller;

import com.example.mqttdemo.pojo.PropertiesUpdateRequest;
import com.example.mqttdemo.pojo.ServiceConfig;
import com.example.mqttdemo.service.MqttService;
import com.google.gson.Gson;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;


@RestController
@RequestMapping("/mqtt")
public class MqttController {

    @Autowired
    private MqttService mqttService;

/*    http://localhost:8091/mqtt/send
    {
        "temp": "18°C",
            "ledStatus": true,
            "airQuality": "60",
            "humidity": 89,
            "bright": 802,
            "airpressure": 1006,
            "airStatus": false
    }*/
    @PostMapping("/send")
    public ResponseEntity<String> sendMessage(@RequestBody PropertiesUpdateRequest request) {
        String topic = "$oc/devices/qq_qq01/sys/properties/report";

        ServiceConfig.Properties properties = new ServiceConfig.Properties();
        properties.updateProperties(request.getTemp(), request.isLedStatus(), request.getAirQuality(), request.getHumidity(), request.getBright(), request.getAirpressure(), request.isAirStatus(), request.isAlarmStatus(), request.getAirTemp());

        ServiceConfig myconfig = ServiceConfig.createServiceConfig("service01", properties);
        try {
            mqttService.publish(topic, new Gson().toJson(myconfig));
            HashMap<String,Object> map = new HashMap<>();
            map.put("code",200);
            map.put("msg","Message sent successfully");
            return ResponseEntity.ok(new Gson().toJson(map));
        } catch (MqttException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to send message: " + e.getMessage());
        }
    }
}